package com.lemon.smartsafety.ui.activity.fire.item;

import android.content.Intent;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.reflect.TypeToken;
import com.ldzs.recyclerlibrary.Mode;
import com.ldzs.recyclerlibrary.PullToRefreshRecyclerView;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.entity.RefreshViewEntity;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.entity.fire.FireCompanyDelete;
import com.lemon.smartsafety.entity.safe.company.CompanyInfo;
import com.lemon.smartsafety.http.HttpBack;
import com.lemon.smartsafety.http.HttpOkBase;
import com.lemon.smartsafety.http.HttpPath;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.listener.RecyclerTClickListener;
import com.lemon.smartsafety.result.BaseMode;
import com.lemon.smartsafety.result.SuperviseSettingHead;
import com.lemon.smartsafety.result.fire.SuperviseSettingTail;
import com.lemon.smartsafetynew.ui.activity.base.NewBaseActivity;
import com.lemon.smartsafety.ui.adapter.fire.FirefightingSetAdapter;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.JsonUtils;
import com.lemon.smartsafety.utils.LogUtils;
import com.lemon.smartsafety.utils.SystemUtil;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.ToastUtil;
import com.lemon.smartsafety.utils.app.ToastUtils;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.smartsafety.view.ViewFireCompanyNone;
import com.lemon.smartsafety.view.ViewFireTop;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

public class FirefightingCompanySetActivity extends NewBaseActivity implements RecyclerTClickListener<SuperviseSettingTail> {


    //刷新顶部的数据
    public static String REFRESH_TOP_TAG = "FirefightingCompanySetActivity_REFRESH_TOP_TAG";
    @Bind(R.id.main_title)
    TextView mainTitle;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.app_bar_layout)
    AppBarLayout appBarLayout;
    @Bind(R.id.fireTop)
    ViewFireTop fireTop;
    @Bind(R.id.txt_search)
    TextView txtSearch;
    @Bind(R.id.et_search)
    EditText etSearch;
    @Bind(R.id.pullToRefreshRecyclerView)
    PullToRefreshRecyclerView mPullToRefreshRecyclerView;
    @Bind(R.id.swipe_layout)
    SwipeRefreshLayout swipeLayout;
    @Bind(R.id.float_button)
    FloatingActionButton floatButton;
    @Bind(R.id.viewFireCompanyNone)
    ViewFireCompanyNone viewFireCompanyNone;


    private FirefightingSetAdapter mAdapter;
    private LinearLayoutManager mLayoutManager;
    private CompanyInfo mCompanyInfo;

    public int page_size = 20;
    public int current_page = 1;
    private boolean isLoadMore = true;

    private List<SuperviseSettingTail> mList;
    private List<SuperviseSettingTail> superviseSettingTailList;

    private SuperviseSettingHead superviseSettingHead;
    private String strSearch = "";


    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(FirefightingCompanySetActivity.this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            callFinish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_firefighting_company_set;
    }

    @Override
    protected void initTitleView() {
        setBarTitle("监督单位设置");
    }

    @Override
    protected void initView() {
        fireTop.setTitleContent("");
        fireTop.setTitleSubContent("");
        fireTop.setNum1Content("");
        fireTop.setNum2Content("");
        fireTop.setNum1Color(R.color.light_green);
        fireTop.setNum2Color(R.color.blue);

        mList = new ArrayList<>();

        mAdapter = new FirefightingSetAdapter(mList, this);


        mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        //mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
        mPullToRefreshRecyclerView.setLayoutManager(mLayoutManager);

        mPullToRefreshRecyclerView.setRefreshMode(Mode.DISABLED);
        mPullToRefreshRecyclerView.setOnPullDownToRefreshListener(new PullToRefreshRecyclerView.OnPullDownToRefreshListener() {
            @Override
            public void onRefresh() {

                //上啦刷新
                if (!CommonUtil.listIsEmpty(mList)) {
                    current_page = current_page + 1;
                    httpList();
                }
            }
        });

        mPullToRefreshRecyclerView.setAdapter(mAdapter);
        //mPullToRefreshRecyclerView.beginRefreshing();

        current_page = 1;
        isLoadMore = true;
        initSwipRefresh();
        mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_END);
        initTopHttp();
        getNetData();
    }

    @Override
    protected void initHttp() {

    }

    @Override
    protected void initList() {
        strSearch = etSearch.getText().toString().trim();
        current_page = 1;
        isLoadMore = true;
        getNetData();
    }

    @Override
    protected void loadList() {

    }

    @Override
    protected void refreshView() {

    }

    @Override
    protected void getBundleArgs() {

        if (getIntent().getExtras() != null) {
            mCompanyInfo = (CompanyInfo) getIntent().getSerializableExtra(BundleKey.COMPANY_INFO);
        }
    }


    private void initSwipRefresh() {

        swipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);


        swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        LogUtils.LOGE("下拉刷新");

                        try {
                            initTopHttp();
                            strSearch = etSearch.getText().toString().trim();
                            current_page = 1;
                            mList.clear();
                            getNetData();
                            swipeLayout.setRefreshing(false);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }, 1000);
            }
        });

    }


    private String getHttpTag() {
        return EventTag.TAG_FIRE_COMPANYSET;
    }


    /**
     * 列表网路请求
     */
    private void getNetData() {
        try {
            LoggerHelper.error(getClass(), "current_page:" + current_page);
            httpList();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * http处理请求的处理
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(HttpCallbackEvent event) {
        if (getHttpTag().equals(event.getTag())) {

        } else if (EventTag.TAG_FIRE_COMPANYSET.equals(event.getTag())) {
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    mHUDUtil.showDoneTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            getNetData();
                        }
                    });
                } else {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        }
    }





    @Subscribe
    public void onEventMainThread(final FireCompanyDelete event) {
        if (FireCompanyDelete.class.getName().equals(event.getTag())) {
            getConfirmDialog("是否删除(" + event.getData().getCompanyName() + ")？", new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    if (which == DialogAction.POSITIVE) {
                        //删除
                        LogUtils.LOGE("删除");
                        deleteHttp(event.getData().getCompanyCode(), event.getmPosition());
                    }
                }
            }).show();
        }
    }


    /**
     * 刷新列表
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(final RefreshViewEntity event) {
        if (FirefightingCompanySetActivity.class.getName().equals(event.getTAG())) {
            try {
                strSearch = etSearch.getText().toString().trim();
                current_page = 1;
                mList.clear();
                getNetData();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //刷新顶部
        else if (REFRESH_TOP_TAG.equals(event.getTAG())) {
            //刷新顶部
            initTopHttp();
        }


    }


    //点击事件
    @Override
    public void onItemClick(SuperviseSettingTail data, int position) {

    }


    @OnClick({R.id.txt_search, R.id.float_button})
    public void onButtonClick(View v) {
        switch (v.getId()) {
            case R.id.txt_search:
                LogUtils.LOGE(txtSearch.getText().toString());
                try {
                    mList.clear();
                    current_page = 1;
                    strSearch = etSearch.getText().toString().trim();

                    getNetData();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.float_button:
                startActivity(new Intent(this, FirefightingCompanySearchActivity.class));
                break;
            default:
                break;
        }
    }


    /**
     * 初始化顶部
     */
    public void initTopHttp() {
        LemonRequestParams params = new LemonRequestParams("application_user_bind", "bind_id", "");

        mHUDUtil.show();
        HttpOkBase.httpBasePost(params, HttpPath.getmBase(HttpPath.Get_supervise_setting_head), "", new HttpOkBase.HttpInterface() {
            @Override
            public void callBackFunction(boolean httpClient, String result) {

                mHUDUtil.hidden();
                if (httpClient) {
                    BaseMode baseMode = JsonUtils.fromJson(result, BaseMode.class);
                    if (!CommonUtil.objIsEmpty(baseMode)) {
                        if (HttpBack.httpBackError(baseMode)) {

                            try {
                                superviseSettingHead = mGson.fromJson(mGson.toJson(baseMode.getResult()), SuperviseSettingHead.class);
                                initTopScore();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        } else {
                            ToastUtils.toastMsg(baseMode.getMsg());
                        }
                    }
                }
            }
        });

    }


    /**
     * 初始化顶部信息
     */
    private void initTopScore() {
        fireTop.setTitleContent("你好," + superviseSettingHead.getUserName() + "监督员");
        fireTop.setTitleSubContent("已设置监督单位");
        fireTop.setNum1Content(superviseSettingHead.getCorrelationUnitCount());
        fireTop.setNum2Content("/" + superviseSettingHead.getSumCount());
        fireTop.setNum1Color(R.color.colorAppGreen);
        fireTop.setNum2Color(R.color.colorAppBlue);

    }


    /**
     *
     */
    private void httpList() {
        SystemUtil.HideKeyboard(this);
        //handler.sendEmptyMessage(HINT_KEYSTORY);

        superviseSettingTailList = new ArrayList<>();
        LemonRequestParams params = new LemonRequestParams("application_user_bind", "bind_id", "");
        params.put("page_size", String.valueOf(page_size));
        params.put("current_page", String.valueOf(current_page));

        params.put("keywords", strSearch);

        mHUDUtil.show();
        HttpOkBase.httpBasePost(params, HttpPath.getmBase(HttpPath.Get_supervise_setting_tail), "", new HttpOkBase.HttpInterface() {
            @Override
            public void callBackFunction(boolean httpClient, String result) {

                mHUDUtil.hidden();
                if (httpClient) {
                    BaseMode baseMode = JsonUtils.fromJson(result, BaseMode.class);
                    if (!CommonUtil.objIsEmpty(baseMode)) {
                        if (HttpBack.httpBackError(baseMode)) {

                            try {
                                superviseSettingTailList = mGson.fromJson(mGson.toJson(baseMode.getResult()), new TypeToken<List<SuperviseSettingTail>>() {
                                }.getType());
                                refreshViews(baseMode.getMsg());
                            } catch (Exception e) {
                                e.printStackTrace();

                            }

                        } else if (baseMode.getCode().equals("1003")) {
                            if (current_page == 1) {
                                isLoadMore = false;
                                mPullToRefreshRecyclerView.setRefreshMode(Mode.DISABLED);
                            }
                            ToastUtil.show(baseMode.getMsg());
                            refreshViews(baseMode.getMsg());
                        } else {

                            ToastUtils.toastMsg(baseMode.getMsg());
                            refreshViews(baseMode.getMsg());
                        }
                        mAdapter.notifyDataSetChanged();
                    }
                } else {
                    if (current_page == 1) {
                        isLoadMore = false;
                        mPullToRefreshRecyclerView.setRefreshMode(Mode.DISABLED);
                    }
                    refreshViews("网络连接失败");
                }
            }
        });
    }


    public void refreshViews(String msg) {
        mHUDUtil.hidden();
        if (!CommonUtil.listIsEmpty(superviseSettingTailList)) {
            mList.addAll(superviseSettingTailList);
            mAdapter.notifyDataSetChanged();
        }

        errorView(msg);

        if (superviseSettingTailList.size() < page_size) {
            isLoadMore = false;
            if(mPullToRefreshRecyclerView.getMode()!=Mode.DISABLED)
            mPullToRefreshRecyclerView.setRefreshMode(Mode.DISABLED);
        } else {
            mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_END);
        }

    }


    /**
     * 错误的情况下 刷新
     */
    public void errorView(String title) {

        LogUtils.LOGE("新的 错误的情况下");
        try {
            if (CommonUtil.listIsEmpty(mList)) {
                viewFireCompanyNone.setVisibility(View.VISIBLE);
                //showSwipLayout(swipeLayout, false);
                if (CommonUtil.strIsEmpty(title)) {
                    viewFireCompanyNone.setContent("没有更多数据");
                    viewFireCompanyNone.setSearch("重试");
                } else {
                    viewFireCompanyNone.setContent(title);
                    viewFireCompanyNone.setSearch("重试");
                }
                viewFireCompanyNone.setAllClick(new ViewFireCompanyNone.AllClick() {
                    @Override
                    public void click() {
                        initList();
                    }
                });
            } else {
                viewFireCompanyNone.setVisibility(View.GONE);
                showSwipLayout(swipeLayout, true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 删除 某项公司
     */
    public void deleteHttp(String company_code, final int position) {
        LemonRequestParams params = new LemonRequestParams("application_user_bind", "bind_id", "");
        params.put("company_code", company_code);

        mHUDUtil.show();
        HttpOkBase.httpBasePost(params, HttpPath.getmBase(HttpPath.Delete_company_user_relation), "", new HttpOkBase.HttpInterface() {
            @Override
            public void callBackFunction(boolean httpClient, String result) {

                mHUDUtil.hidden();
                if (httpClient) {
                    BaseMode baseMode = JsonUtils.fromJson(result, BaseMode.class);
                    if (!CommonUtil.objIsEmpty(baseMode)) {
                        if (HttpBack.httpBackError(baseMode)) {
                            ToastUtils.toastMsg(baseMode.getMsg());
                            //mHUDUtil.showDoneTip(baseMode.getMsg());

                            mList.remove(position);
                            mAdapter.notifyDataSetChanged();

                            //刷新顶部
                            AppService.getBus().post(new RefreshViewEntity(REFRESH_TOP_TAG));
                        } else {
                            mHUDUtil.showErrorTip(baseMode.getMsg());
                        }
                    }
                }
            }
        });

    }


}
